//
//  UITableView+KP.m
//  Keping
//
//  Created by 柯平 on 2017/6/19.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "UITableView+KP.h"
#import <MJRefresh.h>

@implementation UITableView (KP)

-(void)setPageNo:(NSInteger)pageNo
{
    objc_setAssociatedObject(self, @selector(pageNo), @(pageNo), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(NSInteger)pageNo
{
    NSNumber* pageNO = objc_getAssociatedObject(self, _cmd);
    return pageNO.integerValue;
}

-(void)setPageSize:(NSInteger)pageSize
{
    objc_setAssociatedObject(self, @selector(pageSize), @(pageSize), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(NSInteger)pageSize
{
    NSNumber* pageSize = objc_getAssociatedObject(self, _cmd);
    return pageSize.integerValue;
}

-(void)setRefreshHeader:(MJRefreshNormalHeader *)refreshHeader
{
    objc_setAssociatedObject(self, @selector(refreshHeader), refreshHeader, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(MJRefreshNormalHeader *)refreshHeader
{
    return objc_getAssociatedObject(self, _cmd);
}

-(void)setDataList:(NSArray *)dataList
{
    objc_setAssociatedObject(self, @selector(dataList), dataList, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(NSArray *)dataList
{
    return objc_getAssociatedObject(self, _cmd);
}

-(void)addHeaderWithTarget:(id<RefreshProtocol>)target beginRefre:(BOOL)beginRefresh
{
    self.pageSize = 10;
    self.pageNo = 1;
    
    self.refreshHeader = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.pageNo = 1;
        if (target && [target respondsToSelector:@selector(tableViewRefreshHandle:)]) {
            [target tableViewRefreshHandle:self];
        }
    }];
    
    self.refreshHeader.lastUpdatedTimeLabel.hidden = YES;
    self.mj_header = self.refreshHeader;
    
    if (beginRefresh) {
        [self.mj_header beginRefreshing];
    }
}

-(void)addFooterWithTarget:(id<RefreshProtocol>)target
{
    self.pageSize = 10;
    self.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.pageNo ++;
        if (target && [target respondsToSelector:@selector(tableViewRefreshHandle:)]) {
            [target tableViewRefreshHandle:self];
        }
    }];
}

-(void)setRefresDataSource:(NSArray *)dataSource
{
    if ([self.refreshHeader isRefreshing]) {
        [self.refreshHeader endRefreshing];
        if (dataSource == nil || dataSource.count == 0) {
            self.pageNo = 1;
            return;
        }
    }
    if ([self.mj_footer isRefreshing]) {
        [self.mj_footer endRefreshing];
        if (dataSource == nil || dataSource.count == 0) {
            self.pageNo --;
            return;
        }
    }
    
    if (self.pageNo == 1) {
        self.dataList = dataSource.mutableCopy;
    }else{
        NSMutableArray* data = self.dataList.mutableCopy;
        [data addObjectsFromArray:dataSource];
        self.dataList = data;
    }
    [self reloadData];
    
}

@end
